package com.xinhe.web.service;

import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.Projections;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.xinhe.web.common.Result;
import com.xinhe.web.entity.*;
import com.xinhe.web.reposity.LogisticsCompanyRepository;
import com.xinhe.web.response.IdentityView;
import com.xinhe.web.util.Snowflake;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.inject.Provider;
import javax.persistence.EntityManager;

@Service

public class LogisticsCompanyService {
    @Autowired
    private LogisticsCompanyRepository logisticsCompanyRepository;
    //查询工厂
    private JPAQueryFactory queryFactory;
    @Autowired
    private Provider<EntityManager> entityManager;
    @PostConstruct
    public void init() {
        queryFactory = new JPAQueryFactory(entityManager);
    }

    public QueryResults<LogisticsCompany> pageLogisticsCompany(String name, String code, String remark,
                                                               int pageNum, int pageSize) {
        QLogisticsCompany qLogisticsCompany = QLogisticsCompany.logisticsCompany;
        QMember qMember = QMember.member;
        BooleanBuilder builder = new BooleanBuilder();
        if (StringUtils.isNotBlank(name)){
            builder.and(qLogisticsCompany.name.eq(name));
        }
        if (StringUtils.isNotBlank(code)){
            builder.and(qLogisticsCompany.code.eq(code));
        }
        return queryFactory.select(
                        Projections.bean(
                                LogisticsCompany.class,
                                qLogisticsCompany.name,
                                qLogisticsCompany.code,
                                qLogisticsCompany.id
                        )
                ).from(qLogisticsCompany)
                .where(builder).offset(pageNum * pageSize).limit(pageSize).fetchResults();

    }

    public Result delete(Long logisticsCompanyId) {
        logisticsCompanyRepository.deleteById(logisticsCompanyId);
        return Result.ok();
    }

    public Result findById(Long logisticsCompanyId) {
        return Result.ok(logisticsCompanyRepository.findById(logisticsCompanyId).get());
    }

    public Result saveModel(String name, String code, String remark) {
        LogisticsCompany logisticsCompany = new LogisticsCompany();
        logisticsCompany.setId(Snowflake.generateId());
        logisticsCompany.setName(name);
        logisticsCompany.setCode(code);
        logisticsCompanyRepository.save(logisticsCompany);
        return Result.ok();
    }
}
